package com.dc.di.sf.dt;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.axiom.om.OMElement;

import com.dc.di.sf.utils.OMUtils;

public class RecordData implements DTObject<RecordData> {

	public static final String TAG_DATARECORD = "RecordData";

	private DataStructure dataStructure;
	private List<UnitData> unitDatas = new ArrayList<UnitData>();

	public RecordData(DataStructure dataStructure) {
		this.dataStructure = dataStructure;
	}

	/**
	 * @return the unitDataArray
	 */
	public List<UnitData> getUnitDatas() {
		return unitDatas;
	}

	/**
	 * @param unitDataArray
	 *            the unitDataArray to set
	 */
	public void setUnitDatas(List<UnitData> unitDatas) {
		this.unitDatas = unitDatas;
	}

	public OMElement toXML() {
		OMElement record = OMUtils.createOMElement(TAG_DATARECORD);
		for (UnitData unitData : unitDatas)
			record.addChild(unitData.toXML());
		return record;
	}

	public RecordData fromXML(OMElement xml) {
		if (xml != null)
			for (Iterator itr = OMUtils.getChildren(xml, UnitData.TAG_UNITDATA); itr.hasNext();) {
				OMElement data = (OMElement) itr.next();
				DataUnit dataUnit = getUnitData(data);
				unitDatas.add(new UnitData(dataUnit).fromXML(data));
			}
		return this;
	}

	/* (non-Javadoc)
	 * @see com.dc.di.sf.dt.DTObject#toXMLString()
	 */
	public String toXMLString() {
		StringBuilder sb = new StringBuilder();
		sb.append(OMUtils.generateOMElementBeginString(TAG_DATARECORD));
		for (UnitData unitData : unitDatas)
			sb.append(unitData.toXMLString());
		sb.append(OMUtils.generateOMElementEndString(TAG_DATARECORD));
		return sb.toString();
	}

	private DataUnit getUnitData(OMElement data) {
		String idName = OMUtils.getTextOfChild(data, UnitData.TAG_UNITIDNAME);
		for (DataUnit dataUnit : this.dataStructure.getDataUnits())
			if (idName.equals(dataUnit.getIdName())) {
				return dataUnit;
			}
		return null;
	}

	public void addUnitData(UnitData unitData) {
		unitDatas.add(unitData);
	}

	public void removeUnitData(int index) {
		unitDatas.remove(index);
	}

	public void removeUnitData(String idName) {
		int i = indexOfUnitData(idName);
		if (i >= 0)
			removeUnitData(i);
	}

	public int indexOfUnitData(String idName) {
		for (int i = 0; i < unitDatas.size(); i++)
			if (unitDatas.get(i).getUnitIdName().equalsIgnoreCase(idName))
				return i;
		return -1;
	}

}
